package com.mymall.serve.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

@Service
@Order(0)
public class SpringUtil implements ApplicationContextAware {
	private static volatile ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringUtil.applicationContext = applicationContext;

	}

	public static <T> T getBean(Class<T> clazz) {
		check();
		return applicationContext.getBean(clazz);
	}

	public static void publishApplicationEvent(ApplicationEvent event) {
		check();
		applicationContext.publishEvent(event);
	}

	private static void check() {
		if (applicationContext == null) {
			throw new RuntimeException("spring容器没有初始化完成，请保证applicationcontext初始化完成");
		}
	}
	
	// 获取当前环境
    public static String getActiveProfile() {
    	check();
    	Environment envirenment=applicationContext.getEnvironment();
        return envirenment.getActiveProfiles()[0];
    }
}
